package com.mrd.gtimpframe.action;

import com.mrd.framework.utils.SpringUtils;
import com.mrd.gtimpframe.service.ProtocolService;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 * 在线工具包
 * Created by dengdc on 2017/7/21.
 */
@Controller
@RequestMapping("/web/utils")
public class WebUtilAction {
    private Logger log  = LoggerFactory.getLogger(WebUtilAction.class);
    @Autowired
    private ProtocolService protocolService;

    /**
     * 工具包页面
     * @return
     */
    @RequestMapping("/view")
    public String utilsView(){
        return "/gtimpframe/webUtils/utilsVew";
    }

    /**
     * 重新加载Mapper配置
     */
    @RequestMapping("/refreshMybatisMapper")
    @ResponseBody
    public String refreshMybatisMapper(){
        Resource[] resources = new Resource[0];
        try {
            // 检索 Mapper.xml文件
            resources = new PathMatchingResourcePatternResolver().getResources("classpath*:com/mrd/gtimpframe/**/*.xml");
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            log.info("错误的路径表达式");
            return "错误的路径表达式";
        }
        SqlSessionFactory sqlSessionFactory = SpringUtils.getBean(SqlSessionFactory.class);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        StringBuilder errorBuilder = new StringBuilder();
        StringBuilder infoBuilder = new StringBuilder();

        try {
            //清理现有配置
            cleanMybatisMapperConfiguration(configuration);
        } catch (Exception e) {
            e.printStackTrace();
            return "清理配置，異常";
        }

        //逐个文件进行加载
        for (Resource resource : resources) {
            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(),
                        configuration, resource.toString(), configuration.getSqlFragments());
                xmlMapperBuilder.parse();
                String info = "mapper文件[" + resource.getFilename() + "]加载成功\n";
                log.info(info);
                infoBuilder.append(info);
            } catch (Exception e) {
                e.printStackTrace();
                String errorMsg = "mapper文件[" + resource.getFilename() + "]不存在或内容格式不对\n";
                errorBuilder.append(errorMsg);
                log.error(errorMsg);
            }
        }
        if(errorBuilder.length() > 0){
            return  infoBuilder.toString() + errorBuilder.toString() + "刷新完成，出现异常。";
        }else{
            infoBuilder.append("刷新完成，无错误。");
            return infoBuilder.toString();
        }
    }

    /**
     * 重新加载Mapper配置
     */
    @RequestMapping("/reloadProtocolUnite")
    @ResponseBody
    public String reloadProtocolUnite(){
        protocolService.updateAllUniteToEctStatus();
        return "完成";
    }

    /**
     * 清理meybatis配置
     * @param configuration
     * @throws Exception
     */
    private void cleanMybatisMapperConfiguration(Configuration configuration) throws Exception {
        Class<?> classConfig = configuration.getClass();
        clearMap(classConfig, configuration, "mappedStatements");
        clearMap(classConfig, configuration, "caches");
        clearMap(classConfig, configuration, "resultMaps");
        clearMap(classConfig, configuration, "parameterMaps");
        clearMap(classConfig, configuration, "keyGenerators");
        clearMap(classConfig, configuration, "sqlFragments");
        clearSet(classConfig, configuration);
    }

    /**
     * 清理对应文件的内容
     * @param classConfig
     * @param configuration
     * @param fieldName
     * @throws Exception
     */
    private void clearMap(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
        Field field = classConfig.getDeclaredField(fieldName);
        field.setAccessible(true);
        Map mapConfig = (Map) field.get(configuration);
        mapConfig.clear();
    }

    /**
     * 清理所有资源
     */
    private void clearSet(Class<?> classConfig, Configuration configuration) throws Exception {
        Field field = classConfig.getDeclaredField("loadedResources");
        field.setAccessible(true);
        Set setConfig = (Set) field.get(configuration);
        setConfig.clear();
    }
}
